package com.zhku.zhny.admin.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import com.alibaba.fastjson.JSON;
import com.zhku.zhny.admin.constant.ConstantFilePath;
import com.zhku.zhny.admin.exception.RemoveException;
import com.zhku.zhny.admin.exception.SearchException;
import com.zhku.zhny.admin.service.AdminService;
import com.zhku.zhny.admin.service.AdminServiceImpl;
import com.zhku.zhny.domain.SignUp;
import com.zhku.zhny.domain.SignUpPageBean;
import com.zhku.zhny.util.BaseServlet;
import com.zhku.zhny.util.POIUtil;
import com.zhku.zhny.util.RandomIdFactory;

@WebServlet("/info/signUp")
public class SingUpInfoServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;
	private final String themeName = "报名信息";
	private final String []headNames = {"序号","姓名","性别","专业班级","手机号","小组名","自我介绍"};

	/**
	 * 后台添加
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public String add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		SignUp signUpBean = new SignUp();
		try {
			// 获取表单数据
			BeanUtils.populate(signUpBean, request.getParameterMap());
			signUpBean.setId(RandomIdFactory.getRandomId());
			AdminService adminService = new AdminServiceImpl();
			int i = adminService.addSignUpInfo(signUpBean);
			if (i > 0) {
				return "redirect:/admin/success.html";
			}else {
				return "redirect:/admin/fail.html";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "redirect:/admin/fail.html";
		}
	}

	/**
	 * 删除单个
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void removeSingle(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id = request.getParameter("id");
		AdminService adminService = new AdminServiceImpl();
		boolean result = false;
		try {
			result = adminService.removeSignUpById(id);
			response.getWriter().print(result);
		} catch (RemoveException e) {
			e.printStackTrace();
			response.getWriter().print(result);
		}
	}

	/**
	 * 批量删除
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void removeMutiple(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String param = request.getParameter("ids");
		String[] ids = param.split(",");
		AdminService adminService = new AdminServiceImpl();
		boolean result = false;
		try {
			result = adminService.removeSignUpByIds(ids);
			if(result) {
				response.getWriter().print(result);
			}else {
				response.getWriter().print(result);
			}
		} catch (RemoveException e) {
			e.printStackTrace();
			response.getWriter().print(result);
		}
	}

	/**
	 * 修改
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void modify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	/**
	 * 分页查询
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void fySearch(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = request.getParameter("name");
		String phone = request.getParameter("phone");
		String currentPage = request.getParameter("currentPage");
		int pageSize = 10;// 设置每页显示记录数
		//调用业务逻辑
		AdminService adminService = new AdminServiceImpl();
		SignUpPageBean supg = new SignUpPageBean();
		try {
			supg = adminService.findByNameOrPhone(name, phone, currentPage, pageSize);
			String data = JSON.toJSONString(supg);// 将数据封装为json对象
			// 响应回客户端
			response.setContentType("text/html;charset=UTF-8");
			response.getWriter().print(data);
		} catch (SearchException e) {
			e.printStackTrace();
			response.getWriter().print("");
		}
	}
	/**
	 * 查找所有组别的名称
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void searchGroupsName(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		AdminService adminService = new AdminServiceImpl();
		try {
			List<String>names = adminService.findGroupsName();
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().print(JSON.toJSONString(names));
		} catch (SearchException e) {
			e.printStackTrace();
			response.getWriter().print(JSON.toJSONString(""));
		}
	}
	
	/**
	 * 导出excel表格，导出全部报名信息
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void exportAllInfoAsExcel(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		AdminService adminService = new AdminServiceImpl();
		try {
			List<SignUp>list = adminService.findAllSignUp();
			response.reset();
			response.setContentType("application/vnd.ms-excel;chartset=utf-8");
			response.setHeader("Content-Disposition", "attachment;filename="+new String(themeName.getBytes("UTF-8"),"ISO-8859-1")+".xls");
//			POIUtil.exportDataToExcel(response.getOutputStream(), new ExcelTemple(themeName,headNames,JSON.toJSONString(list)));
			POIUtil.exportDataToExcel(response.getOutputStream(), list, themeName, headNames);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 导出excel表格，导出选中的报名信息
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void exportInfoAsExcel(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String param = request.getParameter("ids");
		String []ids = param.split(",");
		AdminService adminService = new AdminServiceImpl();
		try {
			List<SignUp>list = adminService.findSignUpsByIds(ids);
			response.reset();
			response.setContentType("application/vnd.ms-excel;chartset=utf-8");
			response.setHeader("Content-Disposition", "attachment;filename="+new String(themeName.getBytes("UTF-8"),"ISO-8859-1")+".xls");
			POIUtil.exportDataToExcel(response.getOutputStream(), list, themeName, headNames);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 导出单个报名信息为word文档
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void exportInfoAsWord(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id = request.getParameter("id");
		AdminService adminService = new AdminServiceImpl();
		try {
			response.setContentType("application/msword;chartset=utf-8");
			String templeUrl = ConstantFilePath.LOCALWORDFILEPATH + "/signUp.docx";
			SignUp signUp = adminService.findSignUpsById(id);
			String fileName = new String((signUp.getClasses()+"_"+signUp.getName()).getBytes("UTF-8"),"ISO-8859-1");
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename="+fileName+".docx");
			Map<String, String>infoMap = changeBeanToMap(signUp);
			POIUtil.exportDataToWord(templeUrl, response.getOutputStream(), infoMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	private Map<String, String> changeBeanToMap(SignUp signUp) {
		Map<String, String>map = new HashMap<String, String>();
		map.put("${name}", signUp.getName());
		map.put("${gender}", signUp.getGender());
		map.put("${classes}", signUp.getClasses());
		map.put("${group}", signUp.getGroupName());
		map.put("${telephone}", signUp.getTelephone());
		map.put("${introduction}", signUp.getIntroduction());
		return map;
	}

}
